package com.md24housecall.fragment;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.md24housecall.activity.R;
import com.md24housecall.adapter.IHealthPagerAdapter;
import com.md24housecall.fragment.LoginIHealthFragment.OnLoginListener;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.CustomViewPager;

public final class IHealthFragment extends HomeFragment implements View.OnClickListener {
	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	private int mTabPosition = 0;
	private GlobalConstant constant=GlobalConstant.getInstance();
//	private boolean isGetData=false;
	private CustomViewPager mPager;
	private IHealthPagerAdapter adapter;
	private Utils util=Utils.getInstance();
	private LoginIHealthFragment loginFragment=new LoginIHealthFragment();
	private AQuery mAQuery;
	private String userId="",accessToken="",refreshToken="";
//	private CacheManager cacheManager;
	private Fragment[] arrayFragment={new BloodPressureFragment(),new WeightFragment(),new BloodGlucoFragment(),new BloodOxygenFragment(),new ActivityReportFragment()};
	private ImageButton tab_pressure,tab_weight,tab_gluco,tab_oxygen,tab_activity_tracker;
	private RelativeLayout relTab;
	private int width,height;

	public static IHealthFragment newInstance(int tabPosition) {
		IHealthFragment fragment = new IHealthFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initialize() {
		mPager = (CustomViewPager)mainView.findViewById(R.id.viewPager);
		relTab=(RelativeLayout)mainView.findViewById(R.id.relTab);
		width=getActivity().getResources().getDisplayMetrics().widthPixels/5;
		height=(width*100)/200;
		tab_pressure=(ImageButton)mainView.findViewById(R.id.tabPressure);
		tab_pressure.setOnClickListener(this);
		
		tab_weight=(ImageButton)mainView.findViewById(R.id.tabWeight);
		tab_weight.setOnClickListener(this);
		
		tab_gluco=(ImageButton)mainView.findViewById(R.id.tabGluco);
		tab_gluco.setOnClickListener(this);
		
		tab_oxygen=(ImageButton)mainView.findViewById(R.id.tabOxygen);
		tab_oxygen.setOnClickListener(this);
		
		tab_activity_tracker=(ImageButton)mainView.findViewById(R.id.tabActivityTracker);
		tab_activity_tracker.setOnClickListener(this);
		
		tab_pressure.getLayoutParams().width=width;
		tab_pressure.getLayoutParams().height=height;
		tab_weight.getLayoutParams().width=width;
		tab_weight.getLayoutParams().height=height;
		tab_gluco.getLayoutParams().width=width;
		tab_gluco.getLayoutParams().height=height;
		tab_oxygen.getLayoutParams().width=width;
		tab_oxygen.getLayoutParams().height=height;
		tab_activity_tracker.getLayoutParams().width=width;
		tab_activity_tracker.getLayoutParams().height=height;
		onTabPressed(0);
		mPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int index) {
				// TODO Auto-generated method stub
//				MyLog.d(GlobalConstant.TAG, "onPageSelected: "+index);
				onTabPressed(index);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
//				MyLog.d(GlobalConstant.TAG, "onPageScrolled");
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
//				MyLog.d(GlobalConstant.TAG, "onPageScrollStateChanged");
			}
		});
		mAQuery=new AQuery(getActivity());
		mPager.setChildId(R.id.viewPager);
		mPager.setOffscreenPageLimit(arrayFragment.length);
		if(util.getPreferenceString(constant.ACCESSTOKEN_IHEALTH_KEY, getActivity(), "").equals("")){
			relTab.setVisibility(View.GONE);
			adapter=new IHealthPagerAdapter(getChildFragmentManager(), new Fragment[]{loginFragment});
		}else{
			MyLog.d(GlobalConstant.TAG,"has login");
			relTab.setVisibility(View.VISIBLE);
			adapter=new IHealthPagerAdapter(getChildFragmentManager(), arrayFragment);
		}
		loginFragment.setOnLoginListener(new OnLoginListener() {
			
			@Override
			public void onLoginComplete() {
				// TODO Auto-generated method stub
				String url=String.format(UrlBuilder.URL_GETTOKEN_IHEALTH,constant.code);
				MyLog.d(GlobalConstant.TAG,"url get token: "+url);
				mAQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>(){
					public void callback(String url, JSONObject object, com.androidquery.callback.AjaxStatus status) {
						if(object!=null){
							android.util.Log.d(GlobalConstant.TAG,"login complete: "+object.toString());
							try{
								userId=object.getString("UserID");
								accessToken=object.getString("AccessToken");
								refreshToken=object.getString("RefreshToken");
								util.savePreferenceString(constant.USERID_IHEALTH_KEY, getActivity(), userId);
								util.savePreferenceString(constant.ACCESSTOKEN_IHEALTH_KEY, getActivity(), accessToken);
								util.savePreferenceString(constant.REFRESHTOKEN_IHEALTH_KEY, getActivity(), refreshToken);
								adapter=new IHealthPagerAdapter(getChildFragmentManager(), arrayFragment);
								mPager.setAdapter(adapter);
								relTab.setVisibility(View.VISIBLE);
								MyLog.d(GlobalConstant.TAG,"userId: "+userId);
								MyLog.d(GlobalConstant.TAG,"accesstoken: "+accessToken);
								MyLog.d(GlobalConstant.TAG,"refreshtoken: "+refreshToken);
							}catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
							}
						}
					}
				});
			}
		});
		mPager.setAdapter(adapter);
//		
	}

	@Override
	protected View initView(LayoutInflater inflater,ViewGroup container) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.ihealth, container, false);
	}
	
	@Override
	protected void initLayout() {
		// TODO Auto-generated method stub
		try{
			initialize();
		}catch (Exception e) {
			// TODO: handle exception
//			e.printStackTrace();
			MyLog.d(GlobalConstant.TAG, "exception onCreateView HelpFragment: "+e.getMessage());
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}

	private void switchTab(int index){
		mPager.setCurrentItem(index, true);
		onTabPressed(index);
	}

	private void onTabPressed(int index){
		tab_pressure.setImageResource(R.drawable.tab_pressure);
		tab_weight.setImageResource(R.drawable.tab_weight);
		tab_gluco.setImageResource(R.drawable.tab_gluco);
		tab_oxygen.setImageResource(R.drawable.tab_oxygen);
		tab_activity_tracker.setImageResource(R.drawable.tab_activity_tracker);
		switch (index) {
		case 0:
			tab_pressure.setImageResource(R.drawable.tab_selected_pressure);
			break;
		case 1:
			tab_weight.setImageResource(R.drawable.tab_selected_weight);
			break;
		case 2:
			tab_gluco.setImageResource(R.drawable.tab_selected_gluco);
			break;
		case 3:
			tab_oxygen.setImageResource(R.drawable.tab_selected_oxygen);
			break;
		case 4:
			tab_activity_tracker.setImageResource(R.drawable.tab_selected_activity_tracker);
			break;
		default:
			tab_pressure.setImageResource(R.drawable.tab_selected_pressure);
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tabPressure:
			switchTab(0);
			break;
		case R.id.tabWeight:
			switchTab(1);
			break;
		case R.id.tabGluco:
			switchTab(2);
			break;
		case R.id.tabOxygen:
			switchTab(3);
			break;
		case R.id.tabActivityTracker:
			switchTab(4);
			break;
		default:
			switchTab(0);
			break;
		}
	}
}
